import CustomTextArea from '@/components/antd-comp/input/CustomTextArea'
import ThemeBtn from '@/components/antd-comp/theme-btn'
import { useDictStore } from '@/store/dictStore'
import { useBuriedEvent } from '@/util/buried'
import { LoadingOutlined } from '@ant-design/icons'
import { Button, Input, Modal, Select } from 'antd'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useNavigate } from 'react-router-dom'
import IconUpload from '../../../components/antd-comp/icon-upload'
import { createAssistantsApi } from '../../../controllers/API/assistant'
import '../css/styles.css'

const CreateApplication = ({ open, setOpen, dropList, obj, onSave, dataSource = [] }) => {
  // ------埋点------
  const { applicationBuriedEvent } = useBuriedEvent()
  /* 取消 */
  const handleCancel = (e: React.MouseEvent<HTMLElement>) => {
    applicationBuriedEvent({
      page: obj?.id ? '编辑智能体弹窗' : '创建智能体弹窗',
      event_name: '【取消】按钮',
      data_id: obj.id
    })
    setOpen(false)
    setFormData({ name: '', desc: '', logo: '', category_code: '', id: '', query_template: '' })
  }
  const { t } = useTranslation()
  // State for form fields
  const [formData, setFormData] = useState({
    name: '',
    query_template: '',
    desc: '',
    logo: '',
    category_code: '',
    id: ''
  })

  useEffect(() => {
    setFormData({
      ...formData,
      ...obj
    })
    if (obj.id) {
      setFormData({
        ...formData,
        ...obj,
        category_code: obj.category_code ? Number(obj.category_code) : null
      })
    }
  }, [])
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    setLoading(false)
  }, [])
  // State for errors
  const [errors, setErrors] = useState<any>({})

  // Validate form fields
  const validateField = (name, value) => {
    switch (name) {
      case 'name':
        if (!value) return t('build.nameRequired')
        if (value.length > 50) return '名称最多50个字符'
        return ''
      case 'category_code':
        if(dropList.length > 0){
          if (!value) return t('build.category_codeRequired')
        }
        return ''
      case 'desc':
        // if (value.length > 500) return t('build.forBetter')
        if (value && value.length < 20) return t('application.promptForBetter')
        return ''
      default:
        return ''
    }
  }

  const generateAiValidateField = (name, value) => {
    switch (name) {
      case 'name':
        if (!value) return t('build.nameRequired')
        if (value.length > 50) return '名称最多50个字符'
        return ''
      case 'desc':
        if (!value) return 'AI生成icon时描述不能为空'
        return ''
      default:
        return ''
    }
  }

  const generateAiValidateForm = () => {
    const formErrors = {}
    let isValid = true
    Object.keys(formData).forEach(key => {
      const error = generateAiValidateField(key, formData[key])
      if (error) {
        formErrors[key] = error
        isValid = false
      }
    })
    setErrors(formErrors)
    return isValid
  }

  // Handle field change
  const handleChange = (e, type) => {
    const error = validateField(type, e)
    setErrors(prev => ({ ...prev, [type]: error }))
    if (type === 'name') {
      setFormData(prev => ({ ...prev, name: e }))
    } else if (type === 'category_code') {
      setFormData(prev => ({ ...prev, category_code: e }))
    } else if (type === 'desc') {
      setFormData(prev => ({ ...prev, desc: e }))
    } else if (type === 'query_template') {
      setFormData(prev => ({ ...prev, query_template: e }))
    }
  }

  // Validate entire form
  const validateForm = () => {
    const formErrors = {}
    let isValid = true
    Object.keys(formData).forEach(key => {
      const error = validateField(key, formData[key])
      if (error) {
        formErrors[key] = error
        isValid = false
      }
    })
    setErrors(formErrors)
    return isValid
  }
  const { loadDictOptions } = useDictStore()
  // Handle form submission
  const navigate = useNavigate()
  // 异步函数来获取默认Logo
  const defLogoFun = async () => {
    try {
      const res = await loadDictOptions('icon')
      if (res && res.length) {
        return res[Math.floor(Math.random() * res.length)].value
      }
    } catch (error) {
      console.error('Error loading dict options:', error)
    }
  }
  /* 提交 */
  const handleSubmit = async e => {
    e.preventDefault()
    const isValid = validateForm()
    if (isValid) {
      setLoading(true)
      if (formData?.id) {
        onSave(formData)
        return
      }
      /* 没有选择就获取默认logo */
      let logo = formData.logo
      if (!formData.logo) {
        logo = await defLogoFun()
      }
      let query_template = null
      if (formData?.category_code == '100' || formData?.category_code == '101') {
        query_template = formData.query_template
      }
      createAssistantsApi(formData.name, formData.desc, logo, formData.category_code, query_template)
        .then((res: any) => {
          if (res) {
            applicationBuriedEvent({
              page: '创建智能体弹窗',
              event_name: '【确定】按钮',
              data_id: res.id,
              detail: JSON.stringify({ 类型: formData.category_code, 结果: '成功' })
            })
            // eslint-disable-next-line @typescript-eslint/ban-ts-comment
            // @ts-expect-error
            window.assistantCreate = true // 标记新建助手
            /* 引导判断 */
            if (dataSource.length === 0) {
              localStorage.setItem('applicationEditCreate', '1')
            }
            navigate('/applicationEdit/' + res.id)
          }
        })
        .catch(() => {
          applicationBuriedEvent({
            page: '创建智能体弹窗',
            event_name: '【确定】按钮',
            detail: JSON.stringify({ 类型: formData.category_code, 结果: '失败' })
          })
          setLoading(false)
        })
    }
  }
  /**
   * ICON上传组件相关
   */
  const [iconFileList] = useState([])
  const handleSelectPic = pic => {
    setFormData(prev => ({ ...prev, logo: pic }))
  }

  return (
    <>
      <Modal
        width={825}
        className="modal_antcomp_case"
        title={formData?.id ? t('application.appliPageDiaTitleEdit') : t('application.appliPageDiaTitle')}
        open={open}
        style={{ top: '10%' }}
        onCancel={handleCancel}
        maskClosable={false}
        footer={[
          <Button key="cancel" className="closeBtnStyles closeBtnWid" shape="round" onClick={handleCancel}>
            {t('cancel')}
          </Button>,
          <ThemeBtn key="create" disabled={loading} className="closeBtnWid" onClick={handleSubmit}>
            {loading && <LoadingOutlined className="mr-2" />}
            确定
          </ThemeBtn>
        ]}
      >
        <div
          // style={{ overflowY: 'scroll', height: '616px' }}
          style={{ overflowY: 'scroll', height: '416px' }}
          className="flex flex-col gap-4 py-2 pr-1 sm:max-w-[825px]"
        >
          {/* name */}
          <div className="">
            <label htmlFor="name" className="bisheng-label">
              {t('application.appliPageDiaName')}
              <span className="bisheng-tip">*</span>
            </label>
            <Input
              id="name"
              name="name"
              autoComplete="off"
              placeholder="给智能体取个名字，建议4个字以内"
              className="inputHig contMarginTop"
              value={formData.name}
              onChange={e => handleChange(e.target.value, 'name')}
            />
            {errors.name && <p className="bisheng-tip mt-1">{errors.name}</p>}
          </div>
          {/* type */}
          {dropList.length > 0 && 
            <div className="caseMarginTop">
              <label htmlFor="category_code" className="bisheng-label">
                {t('application.appliPageDiaType')}
                <span className="bisheng-tip">*</span>
              </label>
              <div className="contMarginTop">
                <Select
                  key={'createApplication_select'}
                  className="inoutHig"
                  placeholder={t('application.appliPageDiaType')}
                  value={formData.category_code ? formData.category_code : null}
                  style={{ width: '100%' }}
                  onChange={val => handleChange(val, 'category_code')}
                  options={dropList}
                  fieldNames={{ label: 'label', value: 'id' }}
                />
              </div>
              {errors.category_code && <p className="bisheng-tip mt-1">{errors.category_code}</p>}
            </div>
          }
          {/* query_template */}
          {(formData?.category_code == '100' || formData?.category_code == '101') && (
            <div className="caseMarginTop">
              <label htmlFor="query_template" className="bisheng-label">
                输入模版
              </label>
              <CustomTextArea
                id="query_template"
                name="query_template"
                placeholder="输入模版"
                maxLength={200}
                className="contMarginTop min-h-32"
                value={formData.query_template}
                onChange={e => {
                  handleChange(e.target.value, 'query_template')
                }}
              />
              {errors.query_template && <p className="bisheng-tip mt-1">{errors.query_template}</p>}
            </div>
          )}

          {/* desc */}
          <div className="caseMarginTop">
            <label htmlFor="desc" className="bisheng-label">
              {t('application.appliPageDiadesc')}
            </label>
            <CustomTextArea
              id="desc"
              name="desc"
              placeholder={t('application.appliPageDiadescDef')}
              maxLength={200}
              className="contMarginTop min-h-32"
              value={formData.desc}
              onChange={e => {
                handleChange(e.target.value, 'desc')
              }}
            />
            {errors.desc && <p className="bisheng-tip mt-1">{errors.desc}</p>}
          </div>
          {/* icon */}
          <div className="caseMarginTop">
            <IconUpload
              defaultFileList={iconFileList}
              logo={formData.logo}
              name={formData.name}
              description={formData.desc}
              validateMethod={generateAiValidateForm}
              onSelect={pic => handleSelectPic(pic)}
            ></IconUpload>
          </div>
        </div>
      </Modal>
    </>
  )
}

export default CreateApplication
